package com.example.a.musicui;

import android.media.AudioManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;




public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener{


    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView list;

    private MediaPlayer player = new MediaPlayer();

    private ArrayList<Music> musicArrayList;
    private static boolean isExit =false;

    private int number = 0;
    private int status;


    private StatusChangedReceiver receiver;
    private RelativeLayout root_Layout;
    private TextView text_Current;
    private TextView text_Duration;
    private SeekBar seekBar;
    private TextView textView;
    private Handler seekBarHandler;

    private int duration;
    private int time;

    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;

    private static final int MODE_LIST_SEQUENCE = 0;
    private static final int MODE_SINGLE_CYCLE = 1;
    private static final int MODE_LIST_CYCLE = 2;
    private int playmode;

    private TextView tv_vol;
    private SeekBar seekbar_vol;

    private ImageView iv_sleep;
    private Timer timer_sleep;
    private static final boolean NOTSLEEP= false;
    private static final boolean ISSLEEP =true;
    private int sleepminute =20;
    private static  boolean sleepmode;

    private GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();
        registerListeners();
        initMusicList();
        initListView();
        checkMusicfile();
        duration=0;
        time=0;

        bindStatusChangedReceiver();
        initSeekBarHandler();
        startService(new Intent(this, ServiceMusic.class));
        status = ServiceMusic.COMMAND_STOP;
        playmode =MainActivity.MODE_LIST_SEQUENCE;
        sleepmode =MainActivity.NOTSLEEP;
        gestureDetector = new GestureDetector(this, this);
    }

    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(
                ServiceMusic.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    private void findViews() {
        imgBtn_Previous = (ImageButton) findViewById(R.id.main_ibtn_pre);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.main_ibtn_play);
        imgBtn_Stop = (ImageButton) findViewById(R.id.main_ibtn_stop);
        imgBtn_Next = (ImageButton) findViewById(R.id.main_ibtn_next);



        list = (ListView) findViewById(R.id.main_listview);
        textView=(TextView)findViewById(R.id.main_tv_volumeText);
        seekBar = (SeekBar) findViewById(R.id.main_seekBar);
        text_Current = (TextView) findViewById(R.id.main_tv_curtime);
        text_Duration = (TextView) findViewById(R.id.main_tv_totaltime);
        root_Layout = (RelativeLayout) findViewById(R.id.activity_main);
        tv_vol = (TextView)findViewById(R.id.main_tv_volumeText);
        seekbar_vol = (SeekBar)findViewById(R.id.main_sb_volumebar);
        iv_sleep = (ImageView) findViewById(R.id.main_iv_sleep);

    }


    private void registerListeners() {
        imgBtn_Previous.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                sendBroadcastOnCommand(ServiceMusic.COMMAND_PREVIOUS);
            }
        });
        imgBtn_PlayOrPause.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                switch (status) {
                    case ServiceMusic.STATUS_PLAYING:
                        sendBroadcastOnCommand(ServiceMusic.COMMAND_PAUSE);
                        break;
                    case ServiceMusic.STATUS_PAUSED:
                        sendBroadcastOnCommand(ServiceMusic.COMMAND_RESUME);
                        break;
                    case ServiceMusic.COMMAND_STOP:
                        sendBroadcastOnCommand(ServiceMusic.COMMAND_PLAY);
                    default:
                        break;
                }
            }
        });
        imgBtn_Stop.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                sendBroadcastOnCommand(ServiceMusic.COMMAND_STOP);
            }
        });
        imgBtn_Next.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                sendBroadcastOnCommand(ServiceMusic.COMMAND_NEXT);
            }
        });
        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                number = position;
                sendBroadcastOnCommand(ServiceMusic.COMMAND_PLAY);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(status != ServiceMusic.STATUS_STOPPED){
                    time =seekBar.getProgress();

                    text_Current.setText(formatTime(time));

                    sendBroadcastOnCommand(ServiceMusic.COMMAND_SEEK_TO);
                }
                if(status == ServiceMusic.STATUS_PLAYING){

                    sendBroadcastOnCommand(ServiceMusic.COMMAND_SEEK_TO);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
                if(status == ServiceMusic.STATUS_STOPPED){
                    sendBroadcastOnCommand(ServiceMusic.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(ServiceMusic.COMMAND_RESUME);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }

            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }
        });
    }

    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();

        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);

            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);

            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);

            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);

            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);

                if (strArtist.equals("<unknown>")) {
                    strArtist = "无艺术家";
                    Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                    musicArrayList.add(music);
                } else {
                    Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                    musicArrayList.add(music);
                }

            }
        }
    }


    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getmusicName());
            map.put("musicArtist", music.getmusicArtist());
            list_map.add(map);
        }

        String[] from = new String[]{"musicName", "musicArtist"};
        int[] to = {R.id.listview_tv_title_item, R.id.listview_tv_artist_item};

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        list.setAdapter(simpleAdapter);
    }


    private void checkMusicfile() {
        if (musicArrayList.isEmpty()) {
            imgBtn_Next.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Previous.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件", Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Next.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Previous.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        sendBroadcastOnCommand(ServiceMusic.COMMAND_CHECK_IS_PLAYING);
        PropertyBean propetry = new PropertyBean(MainActivity.this);
        String theme = propetry.getTheme();
        setTheme(theme);
        audio_Control();

        if(sleepmode == MainActivity.ISSLEEP)iv_sleep.setVisibility(View.VISIBLE);
        else iv_sleep.setVisibility(View.INVISIBLE);
    }

    private String formatTime(int msec) {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

    private void sendBroadcastOnCommand(int command) {

        Intent intent = new Intent(ServiceMusic.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        switch (command) {
            case ServiceMusic.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case ServiceMusic.COMMAND_SEEK_TO:
                intent.putExtra("time",time);
                break;
            case ServiceMusic.COMMAND_PREVIOUS:
            case ServiceMusic.COMMAND_NEXT:
            case ServiceMusic.COMMAND_PAUSE:
            case ServiceMusic.COMMAND_STOP:
            case ServiceMusic.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    class StatusChangedReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String musicName = intent.getStringExtra("musicName");
            String musicArtist = intent.getStringExtra("musicArtist");
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case ServiceMusic.STATUS_PLAYING:
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000L);
                    text_Duration.setText(formatTime(duration));
                    imgBtn_PlayOrPause.setBackgroundResource(R.mipmap.pause);
                    MainActivity.this.setTitle("正在播放:" + musicName + " - " + musicArtist);
                    break;
                case ServiceMusic.STATUS_PAUSED:
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    imgBtn_PlayOrPause.setBackgroundResource(R.mipmap.play);
                    MainActivity.this.textView.setText(musicArtist + " - " + musicName);
                    break;
                case ServiceMusic.STATUS_STOPPED:
                    time = 0;
                    duration = 0;
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.mipmap.play);
                    break;
                case ServiceMusic.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    if(playmode == MainActivity.MODE_LIST_SEQUENCE)
                    {
                        if (number == MusicList.getMusicList().size() - 1)
                            sendBroadcastOnCommand(ServiceMusic.STATUS_STOPPED);
                        else
                            sendBroadcastOnCommand(ServiceMusic.COMMAND_NEXT);
                    }
                    else if(playmode == MainActivity.MODE_SINGLE_CYCLE)
                        sendBroadcastOnCommand(ServiceMusic.COMMAND_PLAY);
                    else if(playmode == MainActivity.MODE_LIST_CYCLE)
                    {
                        if (number == MusicList.getMusicList().size() - 1)
                        {
                            number =0;
                            sendBroadcastOnCommand(ServiceMusic.COMMAND_PLAY);
                        }else sendBroadcastOnCommand(ServiceMusic.COMMAND_NEXT);
                    }
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.mipmap.play);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (status == ServiceMusic.STATUS_STOPPED) {
            stopService(new Intent(this, ServiceMusic.class));
        }
        super.onDestroy();
    }

    private void setTheme(String theme) {
        if ("彩色".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_color);
        } else if ("花朵".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_mountain);
        } else if ("小狗".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_snow);
        } else if ("女孩".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            root_Layout.setBackgroundResource(R.mipmap.bg_blur);
        }
    }

    //创建菜单
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //处理菜单点击事件

    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.menu_theme:
                new AlertDialog.Builder(this)
                        .setTitle(R.string.zhuti).
                        setItems(R.array.theme,
                                new android.content.DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        String theme = PropertyBean.THEMES[which];
                                        MainActivity.this.setTheme(theme);
                                        PropertyBean property = new PropertyBean(MainActivity.this);
                                        property.setAndSaveTheme(theme);
                                    }
                                }).show();
                break;
            case R.id.menu_about:
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("GRacePlayer")
                        .setMessage(R.string.about2)
                        .show();
                break;
            case R.id.menu_quit:
                new AlertDialog.Builder(this)
                        .setTitle("提示").
                        setMessage(R.string.quit).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                            // System.exit(0);
                            Intent intent =new Intent(MainActivity.this,ServiceMusic.class);
                            stopService(intent);
                            finish();
                        }

                }).setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
            case R.id.menu_playmode:
                String[] mode = new String[] { "顺序播放", "单曲循环", "列表循环" };
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        MainActivity.this);
                builder.setTitle("播放模式");
                builder.setSingleChoiceItems(mode, playmode,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                playmode = arg1;
                            }
                        });
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                switch (playmode) {
                                    case 0:
                                        playmode = MainActivity.MODE_LIST_SEQUENCE;
                                        Toast.makeText(getApplicationContext(), R.string.sequence, Toast.LENGTH_SHORT).show();
                                        break;
                                    case 1:
                                        playmode = MainActivity.MODE_SINGLE_CYCLE;
                                        Toast.makeText(getApplicationContext(), R.string.sibglecycle, Toast.LENGTH_SHORT).show();
                                        break;
                                    case 2:
                                        playmode = MainActivity.MODE_LIST_CYCLE;
                                        Toast.makeText(getApplicationContext(), R.string.listcycle, Toast.LENGTH_SHORT).show();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        });
                builder.create().show();
                break;
            case R.id.menu_sleep:
                showSleepDialog();
                break;
            case R.id.menu_lrc:
                Intent intent =new Intent(MainActivity.this,LrcActivity.class);
                startActivity(intent);
                break;
        }

        return super.onOptionsItemSelected(item);
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int progress;
        switch(keyCode)
        {
            case KeyEvent.KEYCODE_BACK:
                exitByDoubleClick();
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress = seekbar_vol.getProgress();
                if(progress != 0)
                    seekbar_vol.setProgress(progress-1);
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress = seekbar_vol.getProgress();
                if(progress != seekbar_vol.getMax())
                    seekbar_vol.setProgress(progress+1);
                return true;
            default:
                break;
        }
        return false;
    }
    private void exitByDoubleClick()
    {
        Timer timer = null;
        if(isExit == false)
        {
            isExit = true;
            Toast.makeText(this, "再按一次退出程序！", Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {

                public void run() {
                    isExit = false;
                }
            }, 2000);
        }
        else
        {
            //System.exit(0);
            Intent intent =new Intent(MainActivity.this,ServiceMusic.class);
            stopService(intent);
            finish();
        }
    }
    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }
    private void audio_Control()
    {
        //获取音量管理器
        final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        //设置当前调整音量大小只是针对媒体音乐
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        //设置滑动条最大值
        final int max_progress = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekbar_vol.setMax(max_progress);
        //获取当前音量
        int progress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekbar_vol.setProgress(progress);
        tv_vol .setText("音量： "+(progress*100/max_progress)+"%");
        seekbar_vol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                // TODO Auto-generated method stub
                tv_vol .setText("音量： "+(arg1*100)/(max_progress)+"%");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, AudioManager.FLAG_PLAY_SOUND);
            }
        });
    }
    private void showSleepDialog() {
        //先用getLayoutInflater().inflate方法获取布局，用来初始化一个View类对象
        final View userview = this.getLayoutInflater().inflate(R.layout.dialog, null);

        //通过View类的findViewById方法获取到组件对象
        final TextView tv_minute = (TextView) userview.findViewById(R.id.dialog_tv);
        final Switch switch1 = (Switch) userview.findViewById(R.id.dialog_switch);
        final SeekBar seekbar = (SeekBar) userview.findViewById(R.id.dialog_seekbar);

        tv_minute.setText("睡眠于:" + sleepminute + "分钟");
        //根据当前的睡眠状态来确定Switch的状态
        if (sleepmode == MainActivity.ISSLEEP) switch1.setChecked(true);
        seekbar.setMax(60);
        seekbar.setProgress(sleepminute);
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                // TODO Auto-generated method stub
                sleepminute = arg1;
                tv_minute.setText("睡眠于:" + sleepminute + "分钟");

            }
        });
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                sleepmode = arg1;
            }
        });
        //定义定时器任务
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                //System.exit(0);
                Intent intent =new Intent(MainActivity.this,ServiceMusic.class);
                stopService(intent);
                finish();
            }

        };
        //定义对话框以及初始化
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间(0~60分钟)");
        //设置布局
        dialog.setView(userview);
        //设置取消按钮响应事件
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                arg0.dismiss();
            }
        });
        //设置重置按钮响应时间
        dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                if (sleepmode == MainActivity.ISSLEEP) {
                    timerTask.cancel();
                    timer_sleep.cancel();
                }
                sleepmode = MainActivity.NOTSLEEP;
                sleepminute = 20;
                iv_sleep.setVisibility(View.INVISIBLE);
            }
        });
        //设置确定按钮响应事件
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                if (sleepmode == MainActivity.ISSLEEP) {
                    timer_sleep = new Timer();
                    int time = seekbar.getProgress();
                    //启动任务，时间*60秒后执行
                    timer_sleep.schedule(timerTask, time * 60 * 1000);
                    iv_sleep.setVisibility(View.VISIBLE);
                } else {
                    //取消任务
                    timerTask.cancel();
                    if (timer_sleep != null) timer_sleep.cancel();
                    arg0.dismiss();
                    iv_sleep.setVisibility(View.INVISIBLE);
                }
            }
        });

        dialog.show();
    }
    public boolean dispatchTouchEvent(MotionEvent event)
    {
        if(gestureDetector.onTouchEvent(event))
        {
            event.setAction(MotionEvent.ACTION_CANCEL);
        }
        return super.dispatchTouchEvent(event);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        return gestureDetector.onTouchEvent(event);
    }
    @Override
    public boolean onDown(MotionEvent arg0) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
                           float arg3) {
        // TODO Auto-generated method stub
        if(arg0.getX() - arg1.getX() > 150)
        {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, LrcActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.to_right_enter, R.anim.to_right_exit);
            Toast.makeText(getApplicationContext(), "歌词", Toast.LENGTH_SHORT).show();
        }
        return false;
    }
    @Override
    public void onLongPress(MotionEvent arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
                            float arg3) {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public void onShowPress(MotionEvent arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public boolean onSingleTapUp(MotionEvent arg0) {
        // TODO Auto-generated method stub
        return false;
    }
}

